package cn.shequren.communityPeople.home.ui.view;

import android.app.AlertDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.allenliu.versionchecklib.callback.APKDownloadListener;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.daimajia.numberprogressbar.NumberProgressBar;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.basecomm.utils.WpToast;

import java.io.File;
import java.util.List;

import cn.shequren.communityPeople.R;
import cn.shequren.communityPeople.home.bean.VersionBean;
import cn.shequren.communityPeople.home.ui.adapter.UpdateAdapter;

public class VersionUpdateDialog extends AlertDialog implements View.OnClickListener {

    private Context mContext;
    private VersionBean entity;

    private RecyclerView update_rv;
    private TextView update_later;
    private TextView update_now;
    private TextView update_version;
    private NumberProgressBar progressBar;


    public VersionUpdateDialog(Context context) {
        super(context, R.style.VersionUpdateDialog);
    }

    public VersionUpdateDialog(Context context, VersionBean entity) {
        super(context, R.style.VersionUpdateDialog);
        this.mContext = context;
        this.entity = entity;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.module_mine_dialog_version_update);

        //升级描述
        update_rv = findViewById(R.id.update_rv);
        //稍后更新
        update_later = findViewById(R.id.update_later);
        //马上更新
        update_now = findViewById(R.id.update_now);
        //版本号
        update_version = findViewById(R.id.update_version);
        //更新进度条
        progressBar = findViewById(R.id.update_pb);

        progressBar.setMax(100);

        if (!RxDataTool.isNullString(entity.getVersionNum())) {
            update_version.setText("v" + entity.getVersionNum());
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);

        update_rv.setHasFixedSize(true);
        update_rv.setFocusable(false);
        update_rv.setLayoutManager(layoutManager);

        List<String> content_list = entity.getDescr();

        UpdateAdapter adapter_update = new UpdateAdapter(R.layout.module_mine_item_update_content, content_list);
        adapter_update.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//加载动画
        update_rv.setAdapter(adapter_update);

        //强制更新
        if (entity.isCompel()) {
            setCancelable(false);
            setCanceledOnTouchOutside(false);
        }

        update_later.setOnClickListener(this);
        update_now.setOnClickListener(this);
    }

    private boolean checkApkUrl(String apkUrl) {
        String checkStr = apkUrl.substring(apkUrl.length() - 4);
        if (checkStr.equals(".apk")) {
            return true;
        } else {
            return false;
        }

    }

    //检查当前网络是否为Wifi
    private static boolean isWifi(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        assert connectivityManager != null;
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    private void showNetDialog(String apkUrl) {
        new MaterialDialog.Builder(mContext)
                .title("提示")
                .content("当前非wifi网络，是否更新？")
                .positiveText("确认")
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(mContext,R.color.negative_color))
                .positiveColor(ContextCompat.getColor(mContext,R.color.positive_color))
                .onPositive((dialog, which) -> {
                    updateApp(apkUrl);
                    dialog.dismiss();
                })
                .onNegative((dialog, which) -> dialog.dismiss())
                .show();
    }

    private void updateApp(String apkUrl) {
        setCancelable(false);
        setCanceledOnTouchOutside(false);
        update_later.setVisibility(View.GONE);
        update_now.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);

        String sdPath = Environment.getExternalStorageDirectory() + "/";
        String savePath = sdPath + "download/";

        DownloadBuilder builder = AllenVersionChecker
                .getInstance()
                .downloadOnly(crateUIData(apkUrl));

        builder.setDownloadAPKPath(savePath)//设置下载路径
                .setShowNotification(true)//显示状态栏
                .setShowDownloadingDialog(false)//关闭下载弹框
                .setDirectDownload(true)//下载完成后直接安装
                .setForceRedownload(true)//每次均下载
                .setApkDownloadListener(new APKDownloadListener() {
                    @Override
                    public void onDownloading(int progress) {
                        progressBar.setProgress(progress);
                    }

                    @Override
                    public void onDownloadSuccess(File file) {
                        dismiss();

                    }

                    @Override
                    public void onDownloadFail() {
                        WpToast.s(mContext, "下载失败,请稍后重试");

                    }
                }).excuteMission(mContext);//不加这句话无法下载

    }

    /**
     * @return
     * @important 使用请求版本功能，可以在这里设置downloadUrl
     * 这里可以构造UI需要显示的数据
     * UIData 内部是一个Bundle
     */
    private UIData crateUIData(String apkUrl) {
        UIData uiData = UIData.create();
        uiData.setTitle("");
        uiData.setDownloadUrl(apkUrl);
        uiData.setContent("");
        return uiData;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.update_later:
                if (entity.isCompel()) {
                    WpToast.s(mContext, mContext.getResources().getString(R.string.Update_is_very_important));
                } else {
                    dismiss();
                }
                break;
            case R.id.update_now:
                if (!RxDataTool.isNullString(entity.getAppLink())) {
                    if (checkApkUrl(entity.getAppLink())) {
                        //是更新地址
                        if (isWifi(mContext)) {
                            //是wifi状态
                            updateApp(entity.getAppLink());
                        } else {
                            showNetDialog(entity.getAppLink());
                        }

                    }
                }
                break;
        }

    }
}
